/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.lin.dao.impl;

import com.lin.dao.UserDao;
import com.lin.domain.User;
import com.lin.utils.XmlUtils;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;

/**
 *
 * @author sony
 */
public class UserDaoXmlImpl implements UserDao {

    @Override
    public void add(User user) {
        try {
            Document document = XmlUtils.getDocument();
            Element root = document.getRootElement();
            Element new_user = root.addElement("user");
            new_user.addAttribute("id", user.getId());
            new_user.addAttribute("username", user.getUsername());
            new_user.addAttribute("password", user.getPassword());
            new_user.addAttribute("email", user.getEmail());
            new_user.addAttribute("birthday", user.getBirthday().toLocaleString());
            XmlUtils.write2Xml(document);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public User findUser(String username, String password) {
        try {
            Document document = XmlUtils.getDocument();
            Element e = (Element) document.selectSingleNode("//user[@username='" + username + "' and @password='" + password + "' ]");
            if (e == null) {
                return null;
            }else{
                User user = new User();
                user.setId(e.attributeValue("id"));
                user.setUsername(e.attributeValue("username"));
                user.setPassword(e.attributeValue("password"));
                user.setEmail(e.attributeValue("email")); 
                String birthday = e.attributeValue("birthday");
                DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
                user.setBirthday(df.parse(birthday));
                return user;
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public boolean checkUser(String username) {
        try {
            Document document = XmlUtils.getDocument();
            Element e = (Element) document.selectSingleNode("//user[@username='" + username + "' ]");
            if (e == null) {
                return false;
            }else{
                return true;
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }    
}
